package com.example.datajdbc.ext.spring.data.jdbc;

import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.data.jdbc.core.convert.BatchJdbcOperations;
import org.springframework.data.jdbc.core.convert.DataAccessStrategy;
import org.springframework.data.jdbc.core.convert.DefaultDataAccessStrategy;
import org.springframework.data.jdbc.core.convert.InsertStrategyFactory;
import org.springframework.data.jdbc.core.convert.JdbcConverter;
import org.springframework.data.jdbc.core.convert.SqlGeneratorSource;
import org.springframework.data.jdbc.core.convert.SqlParametersFactory;
import org.springframework.data.jdbc.repository.QueryMappingConfiguration;
import org.springframework.data.mapping.callback.EntityCallbacks;
import org.springframework.data.relational.core.dialect.Dialect;
import org.springframework.data.relational.core.mapping.RelationalMappingContext;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;
import org.springframework.data.repository.core.support.TransactionalRepositoryFactoryBeanSupport;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcOperations;
import org.springframework.util.Assert;

import java.io.Serializable;

/**
 * 这个类修改了 {@link JdbcRepositoryFactoryBean} 创建 RepositoryFactorySupport 的处理
 * 返回了专门提供的 MybatisRepositoryFactory
 * <br/>
 * 通过 EnableJdbcRepositories@repositoryFactoryBeanClass 启用此类后
 * 就可以增强 Data Jdbc 创建的 Repository Bean，使其具有继承的 Mybatis Mapper 能力
 * 本质上是委派模式，实际存在 Repository Bean（Data Jdbc 创建） 和 Mapper Bean（Mybatis Spring 创建）两个实例
 *
 * @see org.springframework.data.jdbc.repository.support.JdbcRepositoryFactoryBean
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
public class MybatisRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable>
        extends TransactionalRepositoryFactoryBeanSupport<T, S, ID> {

    private ApplicationEventPublisher publisher;
    private BeanFactory beanFactory;
    private RelationalMappingContext mappingContext;
    private JdbcConverter converter;
    private DataAccessStrategy dataAccessStrategy;
    private QueryMappingConfiguration queryMappingConfiguration = QueryMappingConfiguration.EMPTY;
    private NamedParameterJdbcOperations operations;
    private SqlSession session;
    private EntityCallbacks entityCallbacks;
    private Dialect dialect;

    public MybatisRepositoryFactoryBean(final Class<? extends T> repositoryInterface) {
        super(repositoryInterface);
    }

    @Override
    public void setApplicationEventPublisher(final ApplicationEventPublisher publisher) {

        super.setApplicationEventPublisher(publisher);

        this.publisher = publisher;
    }

    @Override
    protected RepositoryFactorySupport doCreateRepositoryFactory() {

        final MybatisRepositoryFactory mybatisRepositoryFactory = new MybatisRepositoryFactory(this.dataAccessStrategy,
                this.mappingContext,
                this.converter, this.dialect, this.publisher, this.operations, this.session);
        mybatisRepositoryFactory.setQueryMappingConfiguration(this.queryMappingConfiguration);
        mybatisRepositoryFactory.setEntityCallbacks(this.entityCallbacks);
        mybatisRepositoryFactory.setBeanFactory(this.beanFactory);

        return mybatisRepositoryFactory;
    }

    @Autowired
    public void setMappingContext(final RelationalMappingContext mappingContext) {

        Assert.notNull(mappingContext, "MappingContext must not be null");

        super.setMappingContext(mappingContext);
        this.mappingContext = mappingContext;
    }

    @Autowired
    public void setDialect(final Dialect dialect) {

        Assert.notNull(dialect, "Dialect must not be null");

        this.dialect = dialect;
    }

    public void setDataAccessStrategy(final DataAccessStrategy dataAccessStrategy) {

        Assert.notNull(dataAccessStrategy, "DataAccessStrategy must not be null");

        this.dataAccessStrategy = dataAccessStrategy;
    }

    @Autowired(required = false)
    public void setQueryMappingConfiguration(final QueryMappingConfiguration queryMappingConfiguration) {

        Assert.notNull(queryMappingConfiguration, "QueryMappingConfiguration must not be null");

        this.queryMappingConfiguration = queryMappingConfiguration;
    }

    public void setJdbcOperations(final NamedParameterJdbcOperations operations) {

        Assert.notNull(operations, "NamedParameterJdbcOperations must not be null");

        this.operations = operations;
    }

    public void setSqlSession(final SqlSession session) {

        Assert.notNull(session, "SqlSession must not be null");

        this.session = session;
    }

    @Autowired
    public void setConverter(final JdbcConverter converter) {

        Assert.notNull(converter, "JdbcConverter must not be null");

        this.converter = converter;
    }

    @Override
    public void setBeanFactory(final BeanFactory beanFactory) {

        super.setBeanFactory(beanFactory);

        this.beanFactory = beanFactory;
    }

    @Override
    public void afterPropertiesSet() {

        Assert.state(this.mappingContext != null, "MappingContext is required and must not be null");
        Assert.state(this.converter != null, "RelationalConverter is required and must not be null");

        if (this.operations == null) {

            Assert.state(this.beanFactory != null, "If no JdbcOperations are set a BeanFactory must be available");

            this.operations = this.beanFactory.getBean(NamedParameterJdbcOperations.class);
        }

        if (this.session == null) {

            Assert.state(this.beanFactory != null, "If no SqlSession are set a BeanFactory must be available");

            this.session = this.beanFactory.getBean(SqlSession.class);
        }

        if (this.dataAccessStrategy == null) {

            Assert.state(this.beanFactory != null, "If no DataAccessStrategy is set a BeanFactory must be available");

            this.dataAccessStrategy = this.beanFactory.getBeanProvider(DataAccessStrategy.class) //
                    .getIfAvailable(() -> {

                        Assert.state(this.dialect != null, "Dialect is required and must not be null");

                        final SqlGeneratorSource sqlGeneratorSource = new SqlGeneratorSource(this.mappingContext,
                                this.converter,
                                this.dialect);
                        final SqlParametersFactory sqlParametersFactory = new SqlParametersFactory(this.mappingContext,
                                this.converter);
                        final InsertStrategyFactory insertStrategyFactory = new InsertStrategyFactory(this.operations,
                                new BatchJdbcOperations(this.operations.getJdbcOperations()), this.dialect);
                        return new DefaultDataAccessStrategy(sqlGeneratorSource, this.mappingContext, this.converter,
                                this.operations, sqlParametersFactory, insertStrategyFactory);
                    });
        }

        if (this.queryMappingConfiguration == null) {
            this.queryMappingConfiguration = QueryMappingConfiguration.EMPTY;
        }

        if (this.beanFactory != null) {
            this.entityCallbacks = EntityCallbacks.create(this.beanFactory);
        }

        super.afterPropertiesSet();
    }
}
